import os
from typing import List

from flask import send_file
from connector.scenarioConnector import scenarioConnector
from model.scenario import Scenario
import pandas as pd
from datetime import datetime
import uuid
class ScenarioService:
    def __init__(self) -> None:
        return 
    
    # def add_scenario(self,name:str,description:str,key_list,data_list)->None:
        
    #     return 
    
    def getScenarioList(self)->List[Scenario]:
        return scenarioConnector.getScenariosList()
    def addScenarioItem(self,new_scenario_item:dict,scenario_id:str)->None:
        return scenarioConnector.addScenarioItem(new_scenario_item,scenario_id)
    
    def getScenarioById(self,id)->Scenario:
        return scenarioConnector.getScenarioById(id)
    
    def createScenario(self,new_scenario:dict)->None:
        df = pd.read_csv(new_scenario['file'],encoding="gb2312")

        extension = os.path.splitext(new_scenario['image'].filename)[1]
        random_str = str(uuid.uuid4())
    # 创建文件保存的路径
        save_path = os.path.join('./static/image/', random_str+extension)
    # 将文件保存到指定路径
        with open(save_path, 'wb') as destination:
            destination.write(new_scenario['image'].read())
        
        new_scenario.pop('file')
        new_scenario.pop('image')
        new_scenario['attribute_list'] = []
        new_scenario['image'] = random_str+extension
        new_scenario['item_list'] = []
        key_list = df.columns.tolist()
        for index, attribute_name in enumerate(key_list[1:]):
            temp_attribute = {}
            temp_attribute['index'] = index
            temp_attribute['label'] = attribute_name
            temp_attribute['data'] = []
            selected_columns = df.iloc[:, [0, index+1]]
            for index,row in selected_columns.iterrows():
                temp_attribute['data'].append({
                    "date":datetime.strptime(row[0], '%Y/%m/%d'),
                    "value":row[1]
                })
            new_scenario['attribute_list'].append(temp_attribute)
        scenarioConnector.addScenario(new_scenario)
        return
    
    def getFileByName(self,filename):
        try:
            return send_file(f'./static/file/{filename}')
        except Exception as e:
            return str(e)

    def getIamgeByName(self,filename):
        try:
            return send_file(f'./static/image/{filename}')
        except Exception as e:
            return str(e)
        